package com.jiaofamily.localad.sdk.adapters;

import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import android.util.Log;

import com.jiaofamily.localad.sdk.LocalAdLayout;
import com.jiaofamily.localad.sdk.obj.Ration;
import com.jiaofamily.localad.sdk.util.LocalAdUtil;

public abstract class LocalAdAdapter {
	private static final String TAG=LocalAdAdapter.class.getName();
	
	protected WeakReference<LocalAdLayout> layout=null;
	protected Ration ration=null;
	
	public LocalAdAdapter(LocalAdLayout layout, Ration ration){
		this.layout=new WeakReference<LocalAdLayout>(layout);
		this.ration=ration;
	}
	
	public static void handle(LocalAdLayout layout, Ration ration) throws Throwable{
		LocalAdAdapter adapter=getAdapter(layout,ration);
		if(adapter!=null){
			adapter.handle();
		}else{
			throw new Exception("Invaid adapter");
		}
	}
	
	public abstract void handle();
	
	private static LocalAdAdapter getAdapter(LocalAdLayout layout, Ration ration){
		try{
			switch(ration.type){
			case LocalAdUtil.NETWORK_TYPE_ADMOB:
				if(Class.forName("com.google.ads.AdView")!=null){
					return getNetworkAdapter("com.jiaofamily.localad.sdk.adapters.AdMobAdapter",layout,ration);
				}
				break;
			case LocalAdUtil.NETWORK_TYPE_YOUMI:
				if(Class.forName("net.youmi.android.AdView")!=null){
					return getNetworkAdapter("com.jiaofamily.localad.sdk.adapters.YoumiAdapter",layout,ration);
				}
				break;
			case LocalAdUtil.NETWORK_TYPE_WIYUN:
				if(Class.forName("com.wiyun.ad.AdView")!=null){
					return getNetworkAdapter("com.jiaofamily.localad.sdk.adapters.WiyunAdapter",layout,ration);
				}
				break;
			}
		} catch (ClassNotFoundException e){
			return unknownAdNetwork(layout,ration);
		} catch (VerifyError e){
			Log.e(TAG,"Caught VerifyError:",e);
		}
		return unknownAdNetwork(layout,ration);
	}
	
	private static LocalAdAdapter unknownAdNetwork(LocalAdLayout layout, Ration ration){
		Log.w(TAG,"Unsupported ration type: "+ration.type);
		return null;
	}
	
	private static LocalAdAdapter getNetworkAdapter(String networkAdapter, LocalAdLayout layout, Ration ration){
		LocalAdAdapter adapter=null;
		try{
			Class adapterClass=Class.forName(networkAdapter);
			Class[] parameterTypes=new Class[2];
			parameterTypes[0]=LocalAdLayout.class;
			parameterTypes[1]=Ration.class;
			
			Constructor constructor=adapterClass.getConstructor(parameterTypes);
			
			Object[] args=new Object[2];
			args[0]=layout;
			args[1]=ration;
			
			adapter=(LocalAdAdapter) constructor.newInstance(args);
		}catch(ClassNotFoundException e){
			
		}catch(SecurityException e){
			
		}catch(NoSuchMethodException e){
			
		}catch(InvocationTargetException e){
			
		}catch(IllegalAccessException e){
			
		}catch(InstantiationException e){
			
		}
		return adapter;
	}
}
